package me.fung.rem.app.auth

import me.fung.keen.app.view.Presenter
import me.fung.keen.component.message.msg
import me.fung.rem.app.GlobalState
import me.fung.rem.app.encryptor
import me.fung.rem.bean.repo.configAutoSignUp
import me.fung.rem.bean.repo.configCacheInput
import me.fung.rem.bean.repo.configLastLogin
import me.fung.rem.bean.repo.configPassword
import mu.KotlinLogging
import java.text.SimpleDateFormat
import java.util.*

class SignInPresenter : Presenter() {
    val logger = KotlinLogging.logger { }
    val data = SignInModel

    fun signIn() {
        if (data.input.isEmpty()) {
            msg.send { info("输入密码不能为空") }
            return
        }

        val passwordEncryptor = GlobalState.passwordEncryptor()
        if (passwordEncryptor.checkPassword(data.input, configPassword)) {
            GlobalState.authorized = true
            configLastLogin = Date()
            msg.done()
            writeLocalFile()
            logger.info { "登录成功 " + SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date()) }
        } else {
            msg.send { error("密码错误") }
        }
    }

    fun loadLocalFile() {
        data.autoSignIn = configAutoSignUp
        if (!data.autoSignIn) {
            logger.info { "未启用自动登录" }
            return
        }
        data.input = if(configCacheInput=="") "" else encryptor().decrypt(configCacheInput)
    }

    private fun writeLocalFile() {
        configAutoSignUp = data.autoSignIn
        logger.info { "Write Local File auto :$configAutoSignUp" }
        if (data.autoSignIn) {
            configCacheInput = encryptor().encrypt(data.input)
            logger.info { "Write Local File :${data.input}" }
        } else {
            configCacheInput = ""
            logger.info { "Write Local File :" }
        }
    }

}


